using System;
using Sce.Pss.Core.Graphics;
using Sce.Pss.Core;
using Sce.Pss.Core.Imaging;

namespace ResourceManager
{
	public class DrawProvider
	{
		#region Variables
		
		private GraphicsContext _graphics;
		private Matrix4 _projectionMatrix;
		private Matrix4 _viewMatrix;
		private ShaderProgram _textureShaderProgram;
		#endregion
		
		#region Props
		
		public int Width
	    {
	        get {return _graphics.GetFrameBuffer().Width;}
	    }
	
	    public int Height
	    {
	        get {return _graphics.GetFrameBuffer().Height;}
	    }
		
		#endregion
		
		public DrawProvider (GraphicsContext graphics)
		{
			_graphics = graphics;
			_textureShaderProgram = createSimpleTextureShader();
			
			_projectionMatrix = Matrix4.Ortho(0, Width,
	                                         0, Height,
	                                         0.0f, 32768.0f);
			
			_viewMatrix = Matrix4.LookAt(new Vector3(0, Height, 0),
	                                    new Vector3(0, Height, 1),
	                                    new Vector3(0, -1, 0));
		}
		
		public void DrawSprite(Sprite sprite)
	    {
	        var modelMatrix = sprite.CreateModelMatrix();
	        var worldViewProj = _projectionMatrix * _viewMatrix * modelMatrix;
	
	        _textureShaderProgram.SetUniformValue(0, ref worldViewProj);
	
	        _graphics.SetShaderProgram(_textureShaderProgram);
	        _graphics.SetVertexBuffer(0, sprite.Vertices);
	        _graphics.SetTexture(0, sprite.Texture);
	
	        _graphics.Enable(EnableMode.Blend);
	        _graphics.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha);
	
	        _graphics.DrawArrays(DrawMode.TriangleFan, 0, 4);
	    }
		
		public void DrawText(string text, uint argb, Font font, int positionX, int positionY)
	    {
			Sprite sp = new Sprite(text,argb,font,positionX,positionY); 
	        DrawSprite(sp);
			sp.Dispose();
		}
		
		private static ShaderProgram createSimpleTextureShader()
	    {
			var shaderProgram = new ShaderProgram("/Application/Resources/shaders/Texture.cgx");
	
			shaderProgram.SetAttributeBinding(0, "a_Position");
	        shaderProgram.SetAttributeBinding(1, "a_TexCoord");
	
	        shaderProgram.SetUniformBinding(0, "WorldViewProj");
	
	        return shaderProgram;
	    }
	}
}

